package com.log.log.service;

import com.log.log.mapper.OperationLoggerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * packageName com.agridata.log.service
 *
 * @author yanshuanglong
 * @version JDK 8
 * @className OperationLoggerImpl
 * @date 2024/7/31
 * @description TODO
 */
@Service
public class OperationLoggerImpl implements OperationLogger{
    @Autowired
    private OperationLoggerMapper mapper;

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void log(String operationType, String dataTableName, String oldId, String name, String oldValue, String newValue, String username) {
        // 构建列名和值的映射
        Map<String, Object> columns = new HashMap<>();
        columns.put("operation_type", operationType);
        columns.put("table_name", dataTableName);
        columns.put("old_id", oldId);
        columns.put("field_name", name);
        columns.put("old_value", oldValue);
        columns.put("new_value", newValue);
        columns.put("username", username);


        // 执行 SQL 语句
        mapper.addLogRecording(columns);
    }

    @Override
    public Map<String, Object> queryForMap(String tableName, String primaryKeyField, String primaryKeyValue) {
        return mapper.getOldValue(tableName,primaryKeyField,primaryKeyValue);
    }

    private String buildInsertSql(String tableName, Map<String, Object> columns) {
        StringBuilder sql = new StringBuilder();
        sql.append("INSERT INTO ").append(tableName).append(" (");

        // 构建列名部分
        Set<String> columnNames = columns.keySet();
        String columnNamesStr = String.join(", ", columnNames);
        sql.append(columnNamesStr).append(") VALUES (");

        // 构建值部分
        String valuesStr = String.join(", ", columnNames.stream().map(c -> "?").toArray(String[]::new));
        sql.append(valuesStr).append(")");

        return sql.toString();
    }
}
